﻿using System.Collections.Generic;
using System.Configuration;


namespace HikVisionTool.Helper
{
    public class ConfigHelper
    {

        public static Dictionary<string, string> ReadAll(string path)
        {
            Dictionary<string, string> dic = new Dictionary<string, string>();
            ExeConfigurationFileMap map = new ExeConfigurationFileMap
            {
                ExeConfigFilename = path
            };
            Configuration config = ConfigurationManager.OpenMappedExeConfiguration(map, ConfigurationUserLevel.None);
            foreach (string key in config.AppSettings.Settings.AllKeys)
            {
                dic[key] = config.AppSettings.Settings[key].Value;
            }
            return dic;
        }

        public static Dictionary<string, string> ReadAll()
        {
            Dictionary<string, string> dic = new Dictionary<string, string>();
            Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
            foreach (string key in config.AppSettings.Settings.AllKeys)
            {
                dic[key] = config.AppSettings.Settings[key].Value;
            }
            return dic;
        }

        public static void Write(string key, string value)
        {

            Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
            if (config.AppSettings.Settings[key] == null)
            {
                config.AppSettings.Settings.Add(key, value);
            }
            else
            {
                config.AppSettings.Settings[key].Value = value;
            }
            config.Save(ConfigurationSaveMode.Modified);
            ConfigurationManager.RefreshSection("appSettings");//   重新加载新的配置文件   
        }

        public static string ReadValue(Dictionary<string, string> dic,string key)
        {
            foreach (var v in dic)
            {
                if (v.Key == key)
                {
                    return v.Value;
                }
            }
            return "";
        }
    }
}
